package dicebot.apps;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import dicebot.abstracts.MessageHandler;
import dicebot.filene.Main;
import net.mamoe.mirai.event.events.GroupMessageEvent;

public class Sql {
	
	public static Statement getStatement () throws SQLException {
		return DriverManager.getConnection("jdbc:sqlite:db.sqlite").createStatement();
	}
	
	public static void initialize () {
		Main.HANDLERS.add(new MessageHandler() {
			@Override
			public boolean handle(GroupMessageEvent e) throws Exception {
				String msg = e.getMessage().contentToString();
				if (!msg.startsWith(".sql ")) {
					return false;
				}
				String sql = msg.substring(".sql".length());
				Statement statement = getStatement();
				statement.execute(sql);
				ResultSet r = statement.getResultSet();
				if (r != null) {
					String s = "";
					for (int i = 1; i <= r.getMetaData().getColumnCount(); i++) {
						if (i != 1) {
							s += "\t";
						}
						s += r.getMetaData().getColumnName(i);
					}
					while (r.next()) {
						s += "\n";
						for (int i = 1; i <= r.getMetaData().getColumnCount(); i++) {
							if (i != 1) {
								s += "\t";
							}
							s += r.getString(i);
						}
					}
					r.close();
					e.getGroup().sendMessage(s);
				} else {
					e.getGroup().sendMessage("指令执行成功");
				}
				statement.close();
				return true;
			}
		});
	}
}
